package com.gonsin.gview.common.utils;

import org.apache.commons.io.FileUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class ImageUtils {

    /**
     * 获取图片宽度
     * @param file  图片文件
     * @return 宽度
     */
    public static ImageSize getImgWidth(File file) {
        InputStream is = null;
        BufferedImage src = null;
        int width = -1;
        int height = -1;
        try {
            is = new FileInputStream(file);
            src = ImageIO.read(is);
            width = src.getWidth(); // 得到源图宽
            height = src.getHeight();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        ImageSize imageSize = new ImageSize();
        imageSize.width = width;
        imageSize.height = height;
        return imageSize;
    }


    /**
     * 采用指定宽度、高度或压缩比例 的方式对图片进行压缩
     * @param srcfile 源图片地址
     * @param imgdist 目标图片地址
     * @param widthdist 压缩后图片宽度（当rate==null时，必传）
     * @param heightdist 压缩后图片高度（当rate==null时，必传）
     * @param rate 压缩比例
     */
    public static void reduceImg(File srcfile, File imgdist, int widthdist,
                                 int heightdist, Float rate) {
        try {
            // 检查文件是否存在
            if (!srcfile.exists()) {
                return;
            }

            PicUtils picUtils = new PicUtils(srcfile.getAbsolutePath(), imgdist.getAbsolutePath());

            // 如果rate不为空说明是按比例压缩
            if (rate != null && rate > 0) {
                // 获取文件高度和宽度
                ImageSize size = getImgWidth(srcfile);
                if (size == null || size.width == 0 || size.height == 0) {
                    return;
                } else {
                    widthdist = (int) (size.width * rate);
                    heightdist = (int) (size.height * rate);
                }
            }

            picUtils.zoomBySize(widthdist, heightdist);
//            // 开始读取文件并进行压缩
//            Image src = ImageIO.read(srcfile);
//            BufferedImage tag = new BufferedImage((int) widthdist,
//                    (int) heightdist, BufferedImage.TYPE_INT_RGB);
//
//            tag.getGraphics().drawImage(
//                    src.getScaledInstance(widthdist, heightdist,
//                            Image.SCALE_SMOOTH), 0, 0, null);
//
//            FileOutputStream out = new FileOutputStream(imgdist);
//            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
//            encoder.encode(tag);
//            out.close();

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }


    public static void resizePng(File fromFile, File toFile, int outputWidth, int outputHeight,
                                 boolean proportion) {
        try {
            BufferedImage bi2 = ImageIO.read(fromFile);
            if(bi2.getWidth(null) <= outputWidth){
                FileUtils.copyFile(fromFile, toFile);
                return;
            }
            int newWidth;
            int newHeight;
            // 判断是否是等比缩放
            if (proportion) {
                // 为等比缩放计算输出的图片宽度及高度
                double rate1 = ((double) bi2.getWidth(null)) / (double) outputWidth + 0.1;
                double rate2 = ((double) bi2.getHeight(null)) / (double) outputHeight + 0.1;
                // 根据缩放比率大的进行缩放控制
                double rate = rate1 < rate2 ? rate1 : rate2;
                newWidth = (int) (((double) bi2.getWidth(null)) / rate);
                newHeight = (int) (((double) bi2.getHeight(null)) / rate);
            } else {
                newWidth = outputWidth; // 输出的图片宽度
                newHeight = outputHeight; // 输出的图片高度
            }
            BufferedImage to = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = to.createGraphics();
            to = g2d.getDeviceConfiguration().createCompatibleImage(newWidth, newHeight,
                    Transparency.TRANSLUCENT);
            g2d.dispose();
            g2d = to.createGraphics();
            @SuppressWarnings("static-access")
            Image from = bi2.getScaledInstance(newWidth, newHeight, bi2.SCALE_AREA_AVERAGING);
            g2d.drawImage(from, 0, 0, null);
            g2d.dispose();
            ImageIO.write(to, "png", toFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    public static class ImageSize{
        public int width;
        public int height;
    }

}
